package cn.b.sky.mes.hr.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import cn.b.sky.mes.hr.model.PersonnelException;
import cn.b.sky.mes.hr.model.condition.PersonnelExceptionCondition;
import cn.b.sky.mes.hr.service.PersonnelExceptionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.exception.ImeException;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.controller.SecurityController;
import cn.b.sky.mes.cm.enums.ECodeEnums;
import cn.b.sky.user.service.ECodeService;
import cn.b.sky.user.service.model.ECode;

@Controller
@RequestMapping(value = "/personnelException/*")
@Slf4j
public class PersonnelExceptionController extends SecurityController {

  private static final String PERSONNELEXCEPTION_LIST_PAGE = "hr/personnelException/personnelException_list";

  @Resource
  private PersonnelExceptionService personnelExceptionService;

  @Resource
  private ECodeService eCodeService;

  @RequestMapping("personnelException_list")
  public String personnelExceptionListPage(String navTabId,
                                           @ModelAttribute("condition") PersonnelExceptionCondition condition, Model model) {
    model.addAttribute(NAVTABID, navTabId);
    condition.setSiteCode(SecurityContextUtil.getSiteCode());

    List<PersonnelException> list = personnelExceptionService.getPersonnelExceptionListByCondition(condition);
    int count = personnelExceptionService.getPersonnelExceptionCountByCondition(condition);

    condition.setData(list);
    condition.setTotalCount(count);
    model.addAttribute("page", condition);
    return PERSONNELEXCEPTION_LIST_PAGE;
  }

  @RequestMapping("personnelException_add")
  public String addPersonnelException(Model model, String navTabId) {
    List<ECode> ecodes = eCodeService.selectECodeList(ECodeEnums.PERSONNELSKILLLEVELE.getCode(),
        this.getCurrentLanguage());
    model.addAttribute("killLevele", ecodes);
    model.addAttribute(NAVTABID, navTabId);
    return "hr/personnelException/personnelException_add";
  }

  @RequestMapping("savePersonnelException")
  @ResponseBody
  public DWZResult savePersonnelException(PersonnelException pe, Model model, String navTabId) {
    if (pe == null) {
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), SystemConstant.PARAMETERNULL));
    }
    // 结束时间必须大于开始时间,起止时间不得超过24小时
    if (pe.getStartDateTime().after(pe.getEndDateTime())
        || pe.getStartDateTime().equals(pe.getEndDateTime())
        || pe.getEndDateTime().getTime() - pe.getStartDateTime().getTime() > 24 * 60 * 60 * 1000) {
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), "exceptionPeriodOver.M"));
    }
    // 同一个人,同一天 起止时间不得重叠
    pe.setSiteCode(getSiteCode());
    if (!personnelExceptionService.isPeresonnelExceptionValid(pe)) {
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), "exceptionOverlay.M"));
    }
    pe.setSiteCode(this.getSiteCode());
    setCreateInfo(pe);
    personnelExceptionService.insertPersonnelException(pe);

    return dialogAjaxDone(navTabId, null, null, null);
  }

  @RequestMapping("personnelException_edit")
  public String modifyPersonnelException(String id, String navTabId, Model model) {

    if (StringUtils.isBlank(id)) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    Long peId = Long.parseLong(id);
    PersonnelException personnelException = personnelExceptionService.getPersonnelExceptionById(peId);
    model.addAttribute("personnelException", personnelException);
    model.addAttribute(NAVTABID, navTabId);
    List<ECode> ecodes = eCodeService.selectECodeList(ECodeEnums.PERSONNELSKILLLEVELE.getCode(),
        this.getCurrentLanguage());
    model.addAttribute("killLevele", ecodes);
    return "hr/personnelException/personnelException_edit";
  }

  @RequestMapping("personnelException_view")
  public String viewPersonnelException(String id, String navTabId, Model model) {

    if (StringUtils.isBlank(id)) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    Long peId = Long.parseLong(id);
    PersonnelException personnelException = personnelExceptionService.getPersonnelExceptionById(peId);
    model.addAttribute("personnelException", personnelException);
    model.addAttribute(NAVTABID, navTabId);
    List<ECode> ecodes = eCodeService.selectECodeList(ECodeEnums.PERSONNELSKILLLEVELE.getCode(),
        this.getCurrentLanguage());
    model.addAttribute("killLevele", ecodes);
    return "hr/personnelException/personnelException_view";
  }

  @RequestMapping("updatePersonnelException")
  @ResponseBody
  public DWZResult updatePersonnelException(PersonnelException pe, Model model, String navTabId) {
    if (pe == null) {
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), SystemConstant.PARAMETERNULL));
    }
    // 结束时间必须大于开始时间,起止时间不得超过24小时
    if (pe.getStartDateTime().after(pe.getEndDateTime()) 
        || pe.getStartDateTime().equals(pe.getEndDateTime())
        || pe.getEndDateTime().getTime() - pe.getStartDateTime().getTime() > 24 * 60 * 60 * 1000) {
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), "exceptionPeriodOver.M"));
    }
    pe.setSiteCode(this.getSiteCode());
    // 同一个人,同一天 起止时间不得重叠
    if (!personnelExceptionService.isPeresonnelExceptionValid(pe)) {
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), "exceptionOverlay.M"));
    }
    this.setCreateInfo(pe);
    //修改的时候备注置空
    if(StringUtils.isBlank(pe.getMemo())){
      pe.setMemo("");
    }
    personnelExceptionService.updatePersonnelException(pe);

    return dialogAjaxDone(navTabId, null, null, null);
  }

  @RequestMapping("deletePersonnelException")
  @ResponseBody
  public DWZResult deletePersonnelException(String ids, String navTabId, Model model, HttpServletRequest request) {
    if (StringUtils.isBlank(ids)) {
      return ajaxError(getImeViewMessageI18n(null, SystemConstant.PARAMETERNULL));
    }
    String[] idArr = ids.split(",");
    List<BatchJobReport> reports = new ArrayList<BatchJobReport>();
    int failures = 0;
    for (int i = 0; i < idArr.length; i++) {
      String code = idArr[i];
      String message = null;
      try {
        message = personnelExceptionService.deletePersonnelException(Long.parseLong(code));
        message = this.getImeViewMessageI18n(this.getCurrentLanguage(), message);
      } catch (Exception e) {
        log.error("{}", e);
        message = e.getMessage();
      }
      boolean flag = true;
      if (!StringUtils.isBlank(message)) {
        failures += 1;
        flag = false;
      }
      BatchJobReport report = new BatchJobReport(idArr[i], message, flag, this.getCurrentLanguage(), this.getSiteCode());
      reports.add(report);
    }
    if (failures == 0) {
      return navTabAjaxDone(navTabId, null, null, null,
          getImeViewMessageI18n(this.getCurrentLanguage(), "successfulOperation.M"), null);
    } else {
      return batchjobAjaxDone(request, reports);
    }
  }

}
